package com.tnovoselec.android.nfc;

import android.app.Activity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;


public abstract class TechFilterActivity extends Activity {

	@Override
	public void onCreate(Bundle savedState) {
		super.onCreate(savedState);
		init(savedState);

		handleNdefMessages(getNdefMessages(super.getIntent()));
	}

	@Override
	public void onNewIntent(Intent intent) {
		handleNdefMessages(getNdefMessages(intent));
	}

	private NdefMessage[] getNdefMessages(Intent intent) {
		NdefMessage[] msgs = null;
		String action = intent.getAction();

		if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action) || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action) || NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)) {
			Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
			if (rawMsgs != null) {
				msgs = new NdefMessage[rawMsgs.length];
				for (int i = 0; i < rawMsgs.length; i++) {
					msgs[i] = (NdefMessage) rawMsgs[i];
				}
			} else {
				// Unknown tag type.
				byte[] empty = new byte[] {};
				NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty);
				NdefMessage msg = new NdefMessage(new NdefRecord[] { record });
				msgs = new NdefMessage[] { msg };
			}
		}

		return msgs;
	}

	protected abstract void handleNdefMessages(NdefMessage[] messages);

	protected abstract void init(Bundle savedState);
}
